package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone implements Runnable
{
    public synchronized void sendSMS() throws Exception
    {
        System.out.println(Thread.currentThread().getId()+"\t invoked senSMS()");
        sendEmail();
    }

    public synchronized void sendEmail() throws Exception
    {
        System.out.println(Thread.currentThread().getId()+"\t ######invoked sendEmail()");
    }

    Lock lock = new ReentrantLock();
    @Override
    public void run()
    {
        get();
    }

    public void get()
    {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getId()+"\t get()");
            set();
        }finally {
            lock.unlock();
        }
    }

    public void set()
    {
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getId()+"\t ######set()");
        }finally {
            lock.unlock();
        }
    }
}

/**
 * 可重入锁（也叫递归锁）
 * 同一个线程在外层方法获取到锁之后，进入内存方法会自动获取到锁
 */
public class ReenterLockDemo {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(() -> {
            try{
                phone.sendSMS();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t1").start();

        new Thread(() -> {
            try{
                phone.sendSMS();
            }catch (Exception e){
                e.printStackTrace();
            }
        },"t2").start();

        try{
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread t3 = new Thread(phone);
        Thread t4 = new Thread(phone);

        t3.start();
        t4.start();
    }
}
